#!/usr/bin/env python3
"""
验证K线边界修复 - 最终测试
测试2025-06-01到2025-06-11是否包含完整的11根K线
"""

import sys
sys.path.insert(0, '/mnt/i/projects/marketStream/src')

from marketStream.services.backtesting_service_v9 import BacktestingServiceV9
import json
from datetime import datetime

def verify_kline_boundary_fix():
    """验证K线边界修复"""
    print("=" * 80)
    print("🔬 验证K线边界修复 - 最终测试")
    print("=" * 80)

    # 测试参数 - 与bug报告中的参数一致
    symbol = 'ETHUSDT'
    start_time = '2025-06-01'
    end_time = '2025-06-11'
    interval = '1d'

    print(f"\n📊 测试参数 (与bug报告一致):")
    print(f"  - 交易对: {symbol}")
    print(f"  - 开始时间: {start_time}")
    print(f"  - 结束时间: {end_time}")
    print(f"  - 时间周期: {interval}")
    print(f"  - 预期K线数: 11根 (06-01到06-11)")

    # 初始化回测服务
    backtest = BacktestingServiceV9()

    print(f"\n🔄 运行回测...")

    # 运行回测
    result = backtest.run_backtesting(
        symbol=symbol,
        start_time=start_time,
        end_time=end_time,
        interval=interval
    )

    if result['code'] != 200:
        print(f"\n❌ 回测失败: {result['msg']}")
        return False

    print(f"\n✅ 回测完成")
    print(f"  - 返回码: {result['code']}")

    # 获取分析数据
    analyses = result['data']['analyses']
    print(f"\n📈 分析数据验证:")
    print(f"  - 分析次数: {len(analyses)}")

    # 验证K线时间范围
    if analyses:
        first_analysis = analyses[0]
        last_analysis = analyses[-1]

        print(f"\n⏰ 时间范围验证:")
        print(f"  - 第一条分析时间: {first_analysis['time']}")
        print(f"  - 最后一条分析时间: {last_analysis['time']}")

        # 检查是否包含06-11
        has_june_11 = any('2025-06-11' in a['time'] for a in analyses)
        print(f"\n🎯 关键验证:")
        print(f"  - 是否包含06-11的K线: {'✅ 是' if has_june_11 else '❌ 否'}")

        if not has_june_11:
            print(f"\n❌ BUG仍然存在: 缺少06-11的K线!")
            print(f"  实际包含的分析时间:")
            for a in analyses[-5:]:  # 显示最后5条
                print(f"    - {a['time']}")
            return False

        # 验证K线数量
        expected_count = 11
        actual_count = len(analyses)
        print(f"\n📊 K线数量验证:")
        print(f"  - 预期数量: {expected_count}根")
        print(f"  - 实际数量: {actual_count}根")
        print(f"  - 数量匹配: {'✅ 是' if actual_count >= expected_count else '❌ 否'}")

        # 显示所有分析时间
        print(f"\n📝 完整分析时间列表:")
        for i, a in enumerate(analyses, 1):
            print(f"  {i:2d}. {a['time']} - {a['action']}")

    print("\n" + "=" * 80)
    print("✅ K线边界修复验证完成")
    print("=" * 80)

    if has_june_11:
        print("\n🎉 修复成功!")
        print("  - bugfix-v0.3.3中描述的K线缺失问题已解决")
        print("  - 现在可以正确获取06-01到06-11的完整11根K线")
        return True
    else:
        print("\n❌ 修复失败!")
        print("  - 仍然缺少06-11的K线")
        return False

if __name__ == '__main__':
    try:
        success = verify_kline_boundary_fix()
        sys.exit(0 if success else 1)
    except Exception as e:
        print(f"\n❌ 测试过程中出现错误: {str(e)}")
        import traceback
        traceback.print_exc()
        sys.exit(1)
